package com.swinw.asumall.cart.interceptor;

import com.swinw.asumall.cart.controller.CartController;
import com.swinw.asumall.cart.vo.UserInfoVo;
import com.swinw.common.constant.CartConstant;
import com.swinw.common.vo.MemberVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.LinkedHashMap;
import java.util.UUID;

@Component
public class CartInterceptor implements HandlerInterceptor {

    //在同一个线程共享数据
    public static ThreadLocal<UserInfoVo> threadLocal = new ThreadLocal<>();

    /**
     * 在目标方法执行之前执行该方法
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {

        HttpSession session = request.getSession();
        LinkedHashMap<String,Object> memberVo = (LinkedHashMap<String, Object>) session.getAttribute("userLogin");
        UserInfoVo infoVo = new UserInfoVo();
        if(memberVo != null && memberVo.size() > 0){//用户已经登录
            Integer id = (Integer) memberVo.get("id");
            if(id != null){
                infoVo.setUserId(Long.parseLong(""+id));
            }
        }
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length>0){
            for(Cookie cookie : cookies){
                String name = cookie.getName();
                if(name.equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                    infoVo.setUserKey(cookie.getValue());
                }
            }
        }
        //如果临时购物车都没有，那么就创建一个
        if(StringUtils.isEmpty(infoVo.getUserKey())){
            String userKey = UUID.randomUUID().toString();
            infoVo.setUserKey(userKey);
        }

        threadLocal.set(infoVo);
        return true;
    }

    /**
     * 在业务逻辑执行完之后，将临时购物车保存在cookie中
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {

        //如果存在就不保存
        UserInfoVo userInfoVo = threadLocal.get();
        if(!userInfoVo.getTempUser()){
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME,userInfoVo.getUserKey());
            cookie.setDomain("swinw.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
